package io;

import java.io.*;
import java.util.Scanner;

public class IODemo19 {
    public static void main(String[] args) {
        // 1. 读取文件目录
        Scanner in = new Scanner(System.in);
        System.out.println("请输入文件目录：");
        String fileDir = in.next();
        System.out.println("请输入要搜索的词：");
        String word = in.next();

        //2. 参数校验
        File file = new File(fileDir);
        if(!file.isDirectory()){
            System.out.println("输入的目录有误，请确认");
            return;
        }

        // 3. 搜索
        scanDir(file, word);
    }

    private static void scanDir(File file, String word) {
        File[] files = file.listFiles();
        if(files == null){
            return;
        }
        for(File f : files){
            if(f.isFile()){
                //System.out.println(f.getAbsolutePath());
                searchInFile(f, word);
            }else if(f.isDirectory()){
                scanDir(f, word);
            }else{
                // 不操作
            }
        }
    }

    private static void searchInFile(File f, String word) {
        StringBuilder context = new StringBuilder();
        try(InputStream inputStream = new FileInputStream(f)){
            while(true){
                byte[] b = new byte[1024];
                int n = inputStream.read(b);
                if(n == -1){
                    break;
                }
                String s = new String(b, 0, n);
                context.append(s);
            }
            if(context.indexOf(word) != -1){
                System.out.println("找到了！ " + f.getAbsolutePath());
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
